<?php

trait ApiTrait
{
  protected $input = null;
  protected $CODE_OK = 0;
  protected $CODE_UKNOWN = -1;
  protected $CODE_ERROR = 1;

  protected function __apiInit()
  {
   /* Access-Control */
      header('access-control-allow-origin: '. ($_SERVER['HTTP_ORIGIN'] ?? '*'));
      // header('access-control-allow-origin: *');
     header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
    //  header('Access-Control-Allow-Headers: X-Requested-With, Content-Type, Accept');
     header('Access-Control-Allow-Headers: *');
     header('Access-Control-Expose-Headers: *');
     header('Access-Control-Allow-Credentials: true');
     header('Content-Type: application/json; charset=UTF-8');

   // OPTIONS
   if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
     header($_SERVER['SERVER_PROTOCOL'] . ' 204 No Content');
     exit;
   }
   // input variable
   $this->input = RequestInput::getInstance();
  }

  public function unknownReturn($message)
  {
    return [
      'code' => $this->CODE_UKNOWN,
      'msg' => $message,
    ];
  }

  public function errorReturn($message, $errorCode = null)
  {
    return [
      'code' => $errorCode ?? $this->CODE_ERROR, //$errorCode,
      'msg' => $message,
    ];
  }

  public function okReturn($result)
  {
    return [
      'code' => $this->CODE_OK,
      'result' => $result,
    ];
  }


}

class RequestInput
{
  private static $_instance = null;

  private function __construct() {}

  /* 单例 */
  public static function getInstance()
  {
    if (!self::$_instance) {
      self::$_instance = new self();
    }
    return self::$_instance;
  }

  /* 获取 POST for axios */
  public function getPost($field = null, $default = null)
  {
    $input = file_get_contents('php://input');
    if (!$input) {
      $post = [];
    } else {
      $post = json_decode($input, true);
    }
    if (!isset($field)) {
      return $post;
    }
    return $post[$field] ?? $default;
  }
}
